package com.xindaoapp.happypet.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.voice.JsonParser;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rockerhieu.emojicon.EmojiconHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MyClubActivity;
import com.xindaoapp.happypet.activity.PictureEditorActivity;
import com.xindaoapp.happypet.activity.PictureListActivity;
import com.xindaoapp.happypet.adapter.EmptyAdapter;
import com.xindaoapp.happypet.adapter.NotePictureAdapter;
import com.xindaoapp.happypet.adapter.PostsDetailAdapter;
import com.xindaoapp.happypet.adapter.PostsDetailAdapter.onClickDaShang;
import com.xindaoapp.happypet.adapter.SelectAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.DaShangRest;
import com.xindaoapp.happypet.bean.PostLandlordInfos;
import com.xindaoapp.happypet.bean.PostLayerInfo;
import com.xindaoapp.happypet.bean.PostLayerInfos;
import com.xindaoapp.happypet.bean.RecommendInfo;
import com.xindaoapp.happypet.bean.ShareToWeibaResult;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.protocol.IUploadProgress;
import com.xindaoapp.happypet.protocol.PostQueue;
import com.xindaoapp.happypet.protocol.PostQueueImpl;
import com.xindaoapp.happypet.ui.QuoteVideoActivity.VIDEO_TYPE;
import com.xindaoapp.happypet.ui.SkipPageDialog.onSwitchPageChangeListener;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.PUBLISHPOSTS;
import com.xindaoapp.happypet.utils.Expressions;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.utils.PostContentManager;
import com.xindaoapp.happypet.utils.SharePrefUtil;
import com.xindaoapp.share.SharePopupWindow;

/**
 * 帖子详情 <br/>
 * 
 * 必传参数：{@link Constants} KEY_POST_TID <br/>
 * 
 * 可选参数：{@link Constants} KEY_PIDLIST <br/>
 * 
 * 跳转来源 {@link Constants} KEY_POST_FROM_POSTLIST 默认false，调到对应的帖子频道。true：来源对应的帖子频道，直接finish返回
 * 
 * @author xindaoapp
 * 
 */
public class PostDetailActivity extends BaseActivity implements OnClickListener, onClickDaShang,
        onSwitchPageChangeListener {

    private PullToRefreshListView vPullToRefreshListView;
    private View vFirstToolsView;
    private View vSecondToolsView;
    /** 附件选择区域 */
    private View vAccessoryChooseContainerView;
    /** 表情区域 */
    private View vFaceContainerView;
    /** 功能选择 */
    private GridView vSelectView;
    /** 图片列表 */
    private GridView vPhotosGridView;
    /** 引用信息 */
    private View vQuoteInfoView;
    /** 回复内容输入框 */
    private EditText vPostContent;
    private ImageView vQuoteIcon;
    private TextView vQuoteTitle;
    /** 图片viewpager区域 */
    private ViewPager vFaceViewPager;
    /** 小点区域 */
    private LinearLayout vPointContainer;
    private ImageView vLookMode;
    private View vPraiseView;
    private ImageView vImgPraise;
    private ImageView iv_isjing;

    /**
     * 赞过得人 分享的人
     */
    private TextView zanView, shareView;
    private View lay_order, bottom_line;

    /**
     * 打赏
     */
    private PopupWindow mPopupWindow;
    private RelativeLayout lay_scroll;
    private ImageView iv_refresh;
    private Animation operatingAnim;
    private Button bt_ok, bt_no;
    private EditText et_reason;
    private TextView tv_rest, iv_one, iv_two, iv_three, iv_four, iv_five;
    private ProgressBar pb_load;
    private boolean isLoadRest;
    private int mRestCount;
    private int mDaShangCount;
    private TextView tv_dashangsum;
    private String otherPid = "";
    private String mFrom = "";
    private PostLayerInfo mSelectedLayerInfo;
    // private TextView tv_testTextView;
    /**
     * 活动参与人口
     */
    private String mAction = "";
    /**
     * 跳页
     */
    private int mCurrentPage;


    private Toast showToast;
    private TextView hidenText, tv_cancel, tv_sure;
    private ImageView voiceImageView;

    /** 楼主信息 */
    private PostLandlordInfos mPostLandlordInfos;
    /** 发送队列 */
    private PostQueue mPostQueue;
    /** 帖子列表 */
    private PostsDetailAdapter mAdapter;
    /** 图片适配器 */
    private NotePictureAdapter mPictureAdapter;
    private String mForumTid;
    /** 主题Id */
    private String mPidList = null;
    /** 拍照文件地址 */
    private String mCameraFilePath;
    /** 回复的正文内容 */
    private String mPostContent = "";
    private String mTidlist, mTitle;
    /** 楼层pid */
    private final String mLayerPid = "";
    /** 标记当前是引用视频还是引用帖子 */
    private SWITCHSTATE handleFlag = SWITCHSTATE.NONE;
    private SendReceiver mSendReceiver;
    private int mOrder;
    private SelectPicPopupWindow mPopupWindowForMore;

    private SpeechRecognizer mIat;


    private View cancel, makeSure;

    public enum Type {
        showVoice, showInputText, hiddenBottomView, hiddenSoftInput
    }

    public boolean isRefresh = false;


    @Override
    protected int getContentViewResId() {
        return R.layout.activity_posts_detail;
    }

    @Override
    protected void initConfigs() {
        super.initConfigs();
        mForumTid = getIntent().getStringExtra(Constants.KEY_POST_TID);
        mPidList = getIntent().getStringExtra(Constants.KEY_PIDLIST);
    }

    @SuppressLint("ShowToast")
    @Override
    protected void initViews() {
        super.initViews();

        if (getIntent().hasExtra(Constants.KEY_FROM_ACTIVITY)) {
            mAction = getIntent().getStringExtra(Constants.KEY_FROM_ACTIVITY);
        }

        mCurrentPage = 1;

        CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getPath() + "happypet/pic");
        mIat = SpeechRecognizer.createRecognizer(PostDetailActivity.this, mInitListener);
        showToast = Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT);



        vPraiseView = findViewById(R.id.praise);
        vImgPraise = (ImageView) findViewById(R.id.img_praise);// 赞
        vLookMode = (ImageView) findViewById(R.id.look_mode);
        vFirstToolsView = findViewById(R.id.tools_choose);
        vSecondToolsView = findViewById(R.id.reply_tools);
        vFaceContainerView = findViewById(R.id.face);
        vAccessoryChooseContainerView = findViewById(R.id.l_face_picture);
        vSelectView = (GridView) findViewById(R.id.select_list);
        vPhotosGridView = (GridView) findViewById(R.id.picture_list);
        vPostContent = (EditText) findViewById(R.id.content);
        vPostContent.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switchViewState(SWITCHSTATE.NONE);
                return false;
            }
        });
        vQuoteInfoView = findViewById(R.id.quote_post_info);
        vQuoteIcon = (ImageView) findViewById(R.id.icon);
        vQuoteTitle = (TextView) findViewById(R.id.title_desc);
        vPointContainer = (LinearLayout) findViewById(R.id.page_select);
        vFaceViewPager = (ViewPager) findViewById(R.id.viewpager);
        vPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        vSelectView.setAdapter(new SelectAdapter(this));
        vSelectView.setOnItemClickListener(mSelectOnItemClickListener);
        mPictureAdapter = new NotePictureAdapter(getBaseContext(), new ArrayList<String>());
        vPhotosGridView.setAdapter(mPictureAdapter);
        vPhotosGridView.setOnItemClickListener(mOnItemClickListener);
        initFaceView();
        String postMessage = SharePrefUtil.getString(PostDetailActivity.this, mForumTid, null);
        if (postMessage != null) {
            vPostContent.setText(postMessage);
            // vPostContent.setSelection(postMessage.length());
            switchBottomView(Type.hiddenSoftInput);
            hideInputMethod();
        } else {
            switchViewState(SWITCHSTATE.NONE);
        }
        mSendReceiver = new SendReceiver();
        registerReceiver(mSendReceiver, new IntentFilter("com.xindaoapp.com.huifu"));



    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private final TextWatcher mContentTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString())) {
                mPostContent = "";
                return;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

        @Override
        public void afterTextChanged(Editable arg0) {
            mPostContent = EmojiconHandler.getMEmojiCode();
        }

    };

    /**
     * 切换底部按钮的状态
     */
    public void switchBottomView(boolean isFirst) {
        if (isFirst) {
            switchViewState(SWITCHSTATE.NONE);
            vFirstToolsView.setVisibility(View.VISIBLE);
            vSecondToolsView.setVisibility(View.GONE);
        } else {
            vFirstToolsView.setVisibility(View.GONE);
            vSecondToolsView.setVisibility(View.VISIBLE);
            vPostContent.requestFocus();
            vPostContent.setFocusable(true);
            showInputMethod();
        }
    }

    public void switchBottomView(Type type) {
        switch (type) {
            case showVoice:// 直接显示语音输入
                vFirstToolsView.setVisibility(View.GONE);
                vSecondToolsView.setVisibility(View.VISIBLE);
                vPostContent.requestFocus();
                hideInputMethod();
                showVoiceDialog();
                switchViewState(SWITCHSTATE.NONE);
                break;
            case showInputText:// 显示文本输入
                vFirstToolsView.setVisibility(View.GONE);
                vSecondToolsView.setVisibility(View.VISIBLE);
                vPostContent.requestFocus();
                vPostContent.setFocusable(true);
                showInputMethod();
                break;
            case hiddenBottomView:// 隐藏底部输入框布局
                vFirstToolsView.setVisibility(View.VISIBLE);
                vSecondToolsView.setVisibility(View.GONE);
                switchViewState(SWITCHSTATE.NONE);
                hideInputMethod();
                break;
            case hiddenSoftInput:// 隐藏底部布局
                vFirstToolsView.setVisibility(View.GONE);
                vSecondToolsView.setVisibility(View.VISIBLE);
                vPostContent.requestFocus();
                vPostContent.setSelection(vPostContent.length());
                switchViewState(SWITCHSTATE.NONE);
                hideInputMethod();
                break;

        }
    }

    private void setParam() {
        // if (lag.equals("en_us")) {
        // // 设置语言
        // mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        // } else {
        // // 设置语言
        // mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // // 设置语言区域
        // mIat.setParameter(SpeechConstant.ACCENT, lag);
        // }
        // 设置语音前端点
        // mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
        // // 设置语音后端点
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
        // 设置标点符号
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");
        // mIat.setParameter(SpeechConstant.)
        // 设置音频保存路径./////////////
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/iflytek/wavaudio.pcm");
    }

    /**
     * 显示语音输入dialog
     */
    private void showVoiceDialog() {
        setParam();
        mIat.startListening(recognizerListener);
        View view = View.inflate(PostDetailActivity.this, R.layout.view_voicedialog, null);
        cancel = view.findViewById(R.id.cancel);
        makeSure = view.findViewById(R.id.makeSure);
        hidenText = (TextView) view.findViewById(R.id.hidenText);
        tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_sure = (TextView) view.findViewById(R.id.tv_sure);
        voiceImageView = (ImageView) view.findViewById(R.id.voicePic);
        dialog = new Dialog(PostDetailActivity.this, R.style.MyDialog);
        dialog.setContentView(view);
        dialog.setCancelable(false);

        makeSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("说完了".equals(tv_sure.getText().toString())) {
                    mIat.stopListening();
                    // imageView.setVisibility(View.GONE);
                    hidenText.setVisibility(View.VISIBLE);
                    tv_sure.setText("再说一次");
                    hidenText.setText("识别中...");
                } else {
                    tv_sure.setText("说完了");
                    // imageView.setVisibility(View.VISIBLE);
                    // hidenText.setVisibility(View.GONE);
                    mIat.startListening(recognizerListener);
                }
                // dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mIat.cancel();
                dialog.dismiss();
            }
        });

        dialog.show();

    }

    @Override
    protected void initEvents() {
        super.initEvents();
        findViewById(R.id.top_bar_left_imageview).setOnClickListener(this);
        vPraiseView.setOnClickListener(this);
        findViewById(R.id.reply).setOnClickListener(this);
        findViewById(R.id.share).setOnClickListener(this);
        findViewById(R.id.face_button).setOnClickListener(this);
        findViewById(R.id.tool_button).setOnClickListener(this);
        findViewById(R.id.send).setOnClickListener(this);
        findViewById(R.id.top_bar_right_imageview).setOnClickListener(this);
        findViewById(R.id.showVoice).setOnClickListener(this);
        vQuoteInfoView.setOnClickListener(this);
        vPostContent.addTextChangedListener(mContentTextWatcher);
        vLookMode.setOnClickListener(this);
        vPullToRefreshListView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == android.widget.AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    if (TextUtils.isEmpty(vPostContent.getText().toString())) {
                        switchBottomView(Type.hiddenBottomView);
                    } else {
                        switchBottomView(Type.hiddenSoftInput);
                    }
                    // hideInputMethod();
                    if (mAdapter != null) {
                        mAdapter.hidePop();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {}
        });
        vPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                isRefresh = true;
                onLoadDatas();
            }
        });



    }

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        initFirstFloor();
    }

    private View vHeaderView;
    private PostContentManager mPostContentManager;


    /**
     * 初始化楼主
     */
    private void initHandlordView() {
        initPopForDashang();
        if (vHeaderView != null) {
            vPullToRefreshListView.getRefreshableView().removeHeaderView(vHeaderView);
        }
        vHeaderView = View.inflate(getBaseContext(), R.layout.list_item_post_detail_landlord, null);
        ImageView icon = (ImageView) vHeaderView.findViewById(R.id.user_icon);
        bottom_line = vHeaderView.findViewById(R.id.bottom_line);
        lay_order = vHeaderView.findViewById(R.id.lay_order);
        shareView = (TextView) vHeaderView.findViewById(R.id.shareperson);
        zanView = (TextView) vHeaderView.findViewById(R.id.praised);
        iv_isjing = (ImageView) vHeaderView.findViewById(R.id.iv_isjing);
        tv_dashangsum = (TextView) vHeaderView.findViewById(R.id.tv_dashangsum);
        if (Integer.parseInt(mPostLandlordInfos.threadinfo.digest) > 0) {
            iv_isjing.setVisibility(View.VISIBLE);
        } else {
            iv_isjing.setVisibility(View.GONE);
        }

        // TODO 暂时先禁掉打赏记录
        // tv_dashangsum.setVisibility(View.GONE);
        if ("0".equals(mPostLandlordInfos.threadinfo.ratesum)) {
            tv_dashangsum.setVisibility(View.GONE);
        } else {
            tv_dashangsum.setVisibility(View.VISIBLE);
            tv_dashangsum.setText("+" + mPostLandlordInfos.threadinfo.ratesum);
        }

        shareView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getApplicationContext(), ShareRecordListActivity.class);
                intent.putExtra(Constants.KEY_TID, mForumTid);
                startActivity(intent);
            }
        });
        zanView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getBaseContext(), ZanListActivity.class);
                intent.putExtra("tid", mPostLandlordInfos.threadinfo.tid);
                intent.putExtra("totalzan", mPostLandlordInfos.recommendtotal);
                intent.putExtra("title", mPostLandlordInfos.threadinfo.subject);
                startActivity(intent);
            }
        });

        tv_dashangsum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 进入打赏列表
                Intent intent = new Intent(getApplicationContext(), DaShangRecordActivity.class);
                intent.putExtra(Constants.KEY_TID, mForumTid);
                intent.putExtra(Constants.KEY_PID, mPostLandlordInfos.threadinfo.pid);
                startActivity(intent);

            }
        });
        ImageLoader.getInstance().displayImage(mPostLandlordInfos.threadinfo.userface, icon);
        icon.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startUserActivity(mPostLandlordInfos.threadinfo.authorid,
                        mPostLandlordInfos.threadinfo.author,
                        mPostLandlordInfos.threadinfo.userface);
            }
        });
        // 来自活动
        if (mPostLandlordInfos.threadinfo.shaituid > 0) {
            ((TextView) vHeaderView.findViewById(R.id.left_group_name)).setText("来自活动:");
            ((TextView) vHeaderView.findViewById(R.id.group_name))
                    .setText(mPostLandlordInfos.threadinfo.shaitutag);
        } else {
            ((TextView) vHeaderView.findViewById(R.id.left_group_name)).setText("来自圈子:");
            ((TextView) vHeaderView.findViewById(R.id.group_name))
                    .setText(mPostLandlordInfos.threadinfo.forumname);
        }
        vHeaderView.findViewById(R.id.l_from_group).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (getIntent().getBooleanExtra(Constants.KEY_POST_FROM_POSTLIST, false)) {
                    finish();
                } else {
                    if (mPostLandlordInfos.threadinfo.shaituid > 0) {
                        if (getIntent().getBooleanExtra(Constants.KEY_FROM_ACTIVITY, false)) {
                            finish();
                        } else {
                            Intent intent =
                                    new Intent(getBaseContext(), SplashPictureActivity2.class);
                            intent.putExtra("actID",
                                    String.valueOf(mPostLandlordInfos.threadinfo.shaituid));
                            startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent(getBaseContext(), MyClubActivity.class);
                        intent.putExtra("name", mPostLandlordInfos.threadinfo.forumname);
                        intent.putExtra("fId", mPostLandlordInfos.threadinfo.fid);
                        startActivity(intent);
                    }
                }
            }
        });

        // 隐藏查看活动
        // if (mPostLandlordInfos.threadinfo.shaituid > 0) {
        // View shaitu = vHeaderView.findViewById(R.id.look_activity);
        // shaitu.setVisibility(View.VISIBLE);
        // shaitu.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // if (getIntent().getBooleanExtra(Constants.KEY_FROM_ACTIVITY, false)) {
        // finish();
        // } else {
        // Intent intent = new Intent(getBaseContext(), SplashPictureActivity2.class);
        // intent.putExtra("actID",
        // String.valueOf(mPostLandlordInfos.threadinfo.shaituid));
        // startActivity(intent);
        // }
        // }
        // });
        // }

        order = (ImageView) vHeaderView.findViewById(R.id.order);

        // order.setLayoutParams(new LinearLayout.LayoutParams(
        // android.view.ViewGroup.LayoutParams.MATCH_PARENT,
        // (int) ((float) CommonParameter.sScreenWidth / 640 * 70)));
        lay_order.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mOrder == 0) {
                    mOrder = 1;
                    order.setBackgroundResource(R.drawable.postdetail_shunxu);
                    // order.setText("顺序查看");
                } else {
                    mOrder = 0;
                    order.setBackgroundResource(R.drawable.postdetail_daoxu);
                    // order.setText("倒序查看");
                }
                loadLayer();
            }
        });

        ((TextView) vHeaderView.findViewById(R.id.user_name))
                .setText(mPostLandlordInfos.threadinfo.author);
        ((TextView) vHeaderView.findViewById(R.id.time)).setText(CommonUtil
                .formatTimeForDetailCommon(mPostLandlordInfos.threadinfo.addtime));

        handlePraised();

        LinearLayout container = (LinearLayout) vHeaderView.findViewById(R.id.container);
        container.removeAllViews();

        mPostContentManager = new PostContentManager(this, mForumTid);

        container.addView(mPostContentManager.getPostTitle(mPostLandlordInfos.threadinfo.subject));

        mPostContentManager
                .parsePostContainer(container, mPostLandlordInfos.threadinfo.message, -1);
        setLandlordLogo((ImageView) vHeaderView.findViewById(R.id.logo_landlord),
                mPostLandlordInfos.threadinfo.authorid);
        // setPersionPermission((ImageView) vHeaderView.findViewById(R.id.logo_manager),
        // mPostLandlordInfos.threadinfo.member_groupid);

        vPullToRefreshListView.getRefreshableView().addHeaderView(vHeaderView);
        vPullToRefreshListView.setAdapter(new EmptyAdapter(getBaseContext()));

        // 赞，回复，分享
        handleCommentCount();
        handleShareCount();
    }

    /**
     * 设置楼主标志
     * 
     * @param icon
     * @param authorid
     */
    public void setLandlordLogo(ImageView icon, String authorid) {
        if (mPostLandlordInfos.threadinfo.authorid.equals(authorid)) {
            icon.setVisibility(View.VISIBLE);
        } else {
            icon.setVisibility(View.GONE);
        }
    }

    /**
     * 设置管理员标志<br/>
     * 
     * 1为管理员，2为版主，3为版主
     * 
     * @param icon
     * @param memberGroupid
     */
    public void setPersionPermission(ImageView icon, int memberGroupid) {
        if (memberGroupid == 1) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.guanli);
        } else if (memberGroupid == 2) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else if (memberGroupid == 3) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else {
            icon.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取楼主数据
     */
    private void initFirstFloor() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPostFirstDetail(UserState.getUserUid(), mForumTid,
                        new IRequest<PostLandlordInfos>() {
                            @Override
                            public void request(PostLandlordInfos t) {
                                if (null != t && t.getResult().equals("0")) {
                                    mTitle = t.threadinfo.subject;
                                    mPostLandlordInfos = t;
                                    mPostQueue =
                                            new PostQueueImpl(getBaseContext(), UserState
                                                    .getUserUid(),
                                                    mPostLandlordInfos.threadinfo.fid, System
                                                            .currentTimeMillis(), iUploadProgress);

                                    initHandlordView();
                                    loadLayer();
                                    onDataArrived(true);

                                } else if (null != t) {
                                    onDataArrivedEmpty();
                                    showToast(t.getMsg());
                                    HappyPetApplication.mHandler.postDelayed(new Runnable() {

                                        @Override
                                        public void run() {
                                            // TODO Auto-generated method stub
                                            PostDetailActivity.this.finish();
                                        }
                                    }, 2000);
                                } else {
                                    vPullToRefreshListView.onRefreshComplete();
                                    onDataArrived(false);
                                }
                            }
                        });
    }

    private void loadLayer() {
        loadLayer(Constants.PAGE_FIRST);
    }

    /**
     * 加载楼层数据
     * 
     * @param isOnlyAuthor 是否是仅作者
     * @param order 0 正序， 1倒序
     */
    private void loadLayer(final int floor) {
        final boolean isOnlyAuthor = vLookMode.isSelected();
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPostLayerDetail(UserState.getUserUid(), mForumTid, isOnlyAuthor ? "1" : "",
                        mPidList, floor, Constants.PAGE_SIZE, mOrder,
                        new IRequest<PostLayerInfos>() {

                            @Override
                            public void request(PostLayerInfos t) {
                                if (null != t && t.postarray.size() != 0) {
                                    mCurrentPage = floor;
                                    lay_order.setVisibility(View.VISIBLE);
                                    bottom_line.setVisibility(View.VISIBLE);
                                    if (mAdapter == null || isRefresh) {
                                        mAdapter =
                                                new PostsDetailAdapter(mOrder,
                                                        mPostLandlordInfos.threadinfo, mForumTid,
                                                        isOnlyAuthor, PostDetailActivity.this,
                                                        t.postarray, floor, Constants.PAGE_SIZE,
                                                        R.layout.list_item_post_detail_layer,
                                                        R.layout.item_loading);
                                        mAdapter.resetPageNum(floor);
                                        vPullToRefreshListView.setAdapter(mAdapter);
                                    } else {
                                        mAdapter.resetList();
                                        mAdapter.setInitData(t.postarray);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                    mAdapter.setActivity(PostDetailActivity.this);
                                    isRefresh = false;
                                } else if (null != t) {
                                    lay_order.setVisibility(View.GONE);
                                    bottom_line.setVisibility(View.GONE);
                                    // showToast(t.getMsg());
                                }
                                vPullToRefreshListView.onRefreshComplete();

                                /**
                                 * 用于相应参与活动
                                 */
                                if ("canyu".equals(mAction)) {
                                    // showInputMethod();
                                    // findViewById(R.id.reply).performClick();
                                    vPostContent.setFocusable(true);
                                    vPostContent.setFocusableInTouchMode(true);
                                    vPostContent.requestFocus();
                                    vPostContent.setText("参与!");
                                    mAction = "";
                                }
                            }



                        });
    }

    private final OnItemClickListener mSelectOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
                case 0:// 上传图片
                    showPickPhotoPopupWindow();
                    break;
                case 1:// 引用视频
                    showQuoteVideoPopupWindow();
                    break;
                case 2:// 引用帖子
                    quotePost();
                    break;
            }
        }
    };

    private void quotePost() {
        startActivityForResult(new Intent(getBaseContext(), QuotePostActivity.class),
                PUBLISHPOSTS.REQUEST_QUOTE_POST);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_bar_left_imageview:
                finish();
                break;
            case R.id.praise:// 赞
                parse();
                break;
            case R.id.showVoice:
            case R.id.reply:// 回复消息，点击弹出回复框
                if (!CommonUtil.isFastDoubleClick2()) {
                    switchBottomView(Type.showVoice);
                }
                // switchBottomView(Type.showInputText);
                break;
            case R.id.send:// 回复
                if (UserState.isLogged(PostDetailActivity.this) && checkReplyInput()) {
                    post();
                }
                break;
            case R.id.share:// 分享
                share();
                break;
            case R.id.face_button:
                hideInputMethod();
                HappyPetApplication.mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        switchViewState(SWITCHSTATE.FACE);
                    }
                }, 200);
                break;
            case R.id.tool_button:// 选择拍照、视频、引用帖子等功能
                hideInputMethod();
                HappyPetApplication.mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        switchViewState(SWITCHSTATE.TOOLS);
                    }
                }, 200);
                break;
            case R.id.quote_post_info:
                if (handleFlag == SWITCHSTATE.VIDEO) {
                    showDeleteVideoWindow();
                } else if (handleFlag == SWITCHSTATE.POST) {
                    showDeletePostWindow();
                }
                break;
            case R.id.look_mode:// 仅看楼主
                if (mPostLandlordInfos == null) {
                    return;
                }
                if (vLookMode.isSelected()) {// 切换为查看全部
                    vLookMode.setSelected(false);
                    loadLayer();
                } else {// 切换为仅看楼主
                    vLookMode.setSelected(true);
                    loadLayer();
                }
                break;
            case R.id.top_bar_right_imageview:
                // 在这里,根据权限分配操作类型
                if (mPostLandlordInfos == null) {
                    return;
                }
                // TODO 禁掉版主功能
                // showMoreToolsWindow();

                if (UserState.getUser() == null) {
                    // 弹出默认的
                    showMoreToolsWindow();
                    return;
                }

                if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2) {
                    // 弹出第一个
                    showPopForManager(false);
                } else if (UserState.getUser().adminid == 3
                        && UserState.getUser().moderatefids.contains("'"
                                + mPostLandlordInfos.threadinfo.fid + "'")) {
                    // 弹出第一个
                    showPopForManager(false);
                } else if (UserState.getUser().uid.equals(mPostLandlordInfos.threadinfo.authorid)) {
                    // 弹出第二个
                    showPopForManager(true);
                } else {
                    // 弹出默认的
                    showMoreToolsWindow();
                }
                break;
        }
    }


    /**
     * 自己查看自己的帖子 | 管理员查看帖子 或者 版主查看自己板块的帖子
     */
    private void showPopForManager(boolean isSelf) {
        // TODO Auto-generated method stub
        mPopupWindowForMore = new SelectPicPopupWindow(false, R.color.black, this);
        View view = View.inflate(getBaseContext(), R.layout.pop_tools_more1, null);
        LinearLayout layout_manage = (LinearLayout) view.findViewById(R.id.layout_manage);
        if (isSelf) {
            layout_manage.setVisibility(View.GONE);
        } else {
            layout_manage.setVisibility(View.VISIBLE);
        }

        ImageView collect = (ImageView) view.findViewById(R.id.img_collect);
        collect.setSelected(mPostLandlordInfos.threadinfo.myfavorite == 1 ? true : false);
        ImageView skip = (ImageView) view.findViewById(R.id.img_skip_page);
        ImageView delete = (ImageView) view.findViewById(R.id.img_delete);
        ImageView addJing = (ImageView) view.findViewById(R.id.img_addjing);
        ImageView daShang = (ImageView) view.findViewById(R.id.img_dashang);

        collect.setOnClickListener(mPopOnClickListener);
        skip.setOnClickListener(mPopOnClickListener);
        delete.setOnClickListener(mPopOnClickListener);
        addJing.setOnClickListener(mPopOnClickListener);
        daShang.setOnClickListener(mPopOnClickListener);

        mPopupWindowForMore.init(view).showAsDropDown(findViewById(R.id.title));


    }

    // pop的点击监听器
    OnClickListener mPopOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.img_collect:
                    goCollect();
                    break;
                case R.id.img_skip_page:
                    goSkipPage();
                    break;
                case R.id.img_delete:
                    goDelete();
                    break;
                case R.id.img_addjing:
                    goAddJing();
                    break;
                case R.id.img_dashang:
                    mFrom = "right";
                    goDaShang();
                    break;
                case R.id.img_report:
                    goReport();
                    break;

                default:
                    break;
            }
        }


    };

    private void handleShareCount() {
        TextView reply = (TextView) findViewById(R.id.tv_share);
        if (mPostLandlordInfos.threadinfo.sharetimes == 0) {
            reply.setText("分享");
        } else {
            reply.setText(String.valueOf(mPostLandlordInfos.threadinfo.sharetimes));
        }
    }

    /**
     * 举报
     */
    protected void goReport() {
        mPopupWindowForMore.dismiss();

        if (UserState.isLogged(PostDetailActivity.this)) {

            getMoccaApi().report(mForumTid, UserState.getUserUid(),
                    mPostLandlordInfos.threadinfo.pid, new IRequest<BaseEntity>() {

                        @Override
                        public void request(BaseEntity t) {
                            if (null != t) {
                                if (t.getResult().equals("0")) {
                                    mPostLandlordInfos.threadinfo.myfavorite = 0;
                                    showToast("举报成功");
                                } else {
                                    showToast(t.getMsg());
                                }
                            } else {
                                showToast(getResources().getString(R.string.net_error));
                            }
                        }
                    });


        }
    }

    /**
     * 打赏
     */
    protected void goDaShang() {
        // TODO Auto-generated method stub
        mPopupWindowForMore.dismiss();
        showDaShangPop();

    }

    /**
     * 加精
     */
    protected void goAddJing() {
        mPopupWindowForMore.dismiss();
        if (Integer.parseInt(mPostLandlordInfos.threadinfo.digest) > 0) {
            showToast("已经是精华帖了!");
            return;
        }
        getMoccaApi().addJing(mForumTid, new IRequest<BaseEntity>() {

            @Override
            public void request(BaseEntity t) {

                if (null != t) {
                    if (t.getResult().equals("0")) {
                        mPostLandlordInfos.threadinfo.digest = "1";
                        iv_isjing.setVisibility(View.VISIBLE);
                        showToast("加精成功");
                    } else {
                        iv_isjing.setVisibility(View.GONE);
                        showToast(t.getMsg());
                    }
                } else {
                    showToast(getResources().getString(R.string.net_error));
                }
            }
        });

    }

    /**
     * 删帖
     */
    protected void goDelete() {
        // TODO Auto-generated method stub
        mPopupWindowForMore.dismiss();
        new AlertDialog.Builder(PostDetailActivity.this).setMessage("确定删除该帖子吗?").setTitle("提示")
                .setNegativeButton("删除", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getMoccaApi().deletePost(mForumTid, new IRequest<BaseEntity>() {

                            @Override
                            public void request(BaseEntity t) {
                                if (null != t) {
                                    if (t.getResult().equals("0")) {
                                        showToast("删除成功");
                                        finish();
                                    } else {
                                        showToast(t.getMsg());
                                    }
                                } else {
                                    showToast(getResources().getString(R.string.net_error));
                                }
                            }
                        });
                    }
                }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();



    }

    /**
     * 跳页
     */
    private void goSkipPage() {
        // TODO Auto-generated method stub

        mPopupWindowForMore.dismiss();
        new SkipPageDialog(
                PostDetailActivity.this,
                R.style.Default_Dialog_Style,
                mCurrentPage,
                mPostLandlordInfos.threadinfo.replies % 10 == 0 ? mPostLandlordInfos.threadinfo.replies / 10
                        : mPostLandlordInfos.threadinfo.replies / 10 + 1, new IRequest<Integer>() {

                    @Override
                    public void request(Integer t) {
                        loadLayer(t);
                    }
                }).show();
        // new SkipPageDialog(
        // PostDetailActivity.this,
        // R.style.Default_Dialog_Style,
        // mAdapter == null ? 1 : (mAdapter.getCount() % 10 == 0 ? mAdapter.getCount() / 10
        // : mAdapter.getCount() / 10 + 1),
        // mPostLandlordInfos.threadinfo.replies % 10 == 0 ? mPostLandlordInfos.threadinfo.replies /
        // 10
        // : mPostLandlordInfos.threadinfo.replies / 10 + 1, new IRequest<Integer>() {
        //
        // @Override
        // public void request(Integer t) {
        // loadLayer(t);
        // }
        // }).show();

    }

    /**
     * 收藏
     */
    protected void goCollect() {
        // TODO Auto-generated method stub
        mPopupWindowForMore.dismiss();
        if (!UserState.isLogged(PostDetailActivity.this)) {
            return;
        }
        if (mPostLandlordInfos.threadinfo.myfavorite == 0) {
            getMoccaApi().collect(mForumTid, UserState.getUserUid(), new IRequest<BaseEntity>() {

                @Override
                public void request(BaseEntity t) {
                    if (null != t) {
                        if (t.getResult().equals("0")) {
                            mPostLandlordInfos.threadinfo.myfavorite = 1;
                            showToast("收藏成功");
                        } else {
                            showToast(t.getMsg());
                        }
                    } else {
                        showToast(getResources().getString(R.string.net_error));
                    }

                }
            });
        } else {
            getMoccaApi().cancelCollect(mForumTid, UserState.getUserUid(),
                    new IRequest<BaseEntity>() {

                        @Override
                        public void request(BaseEntity t) {
                            if (null != t) {
                                if (t.getResult().equals("0")) {
                                    mPostLandlordInfos.threadinfo.myfavorite = 0;
                                    showToast("取消收藏成功");
                                } else {
                                    showToast(t.getMsg());
                                }
                            } else {
                                showToast(getResources().getString(R.string.net_error));
                            }
                        }
                    });
        }


    }

    private void handleCommentCount() {
        TextView reply = (TextView) findViewById(R.id.tv_reply);
        if (mPostLandlordInfos.threadinfo.replies == 0) {
            reply.setText("回复");
        } else {
            reply.setText(String.valueOf(mPostLandlordInfos.threadinfo.replies));
        }
    }

    public void startUserActivity(String uid, String username, String userface) {
        Intent intent =
                new Intent(getBaseContext(), com.xindaoapp.happypet.activity.MainActivity.class);
        intent.putExtra(Constants.KEY_SKIP_CLASS_NAME, UserInfoFragment.class.getCanonicalName());
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_UID, uid);
        bundle.putString(Constants.KEY_USERNAME, username);
        bundle.putString(Constants.KEY_USERFACE, userface);
        intent.putExtra(Constants.KEY_BUNDLE, bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 处理点赞
     */
    private void handlePraised() {

        TextView praise = (TextView) findViewById(R.id.tv_praise);
        if (mPostLandlordInfos.recommendtotal == 0) {
            praise.setText("赞");
        } else {
            praise.setText(String.valueOf(mPostLandlordInfos.recommendtotal));
        }

        if (mPostLandlordInfos.threadinfo.myrecommend == 1) {
            vImgPraise.setSelected(true);
            // vPraiseView.setEnabled(false);
        } else {
            // vPraiseView.setSelected(false);
            vImgPraise.setSelected(false);
        }

        if (mPostLandlordInfos.recommendtotal == 0) {
            zanView.setText("赞过的人");
        } else {
            zanView.setText("赞过的人" + "(" + mPostLandlordInfos.recommendtotal + ")");
        }
        if (mPostLandlordInfos.threadinfo.sharetimes == 0) {
            shareView.setText("分享的人");
        } else {
            shareView.setText("分享的人" + "(" + mPostLandlordInfos.threadinfo.sharetimes + ")");
        }

        /** 暂时去掉这种形式 */
        // if (mPostLandlordInfos.recommendtotal > 0) {
        // vHeaderView.findViewById(R.id.l_praised).setVisibility(View.VISIBLE);
        // TextView praised = (TextView) vHeaderView.findViewById(R.id.praised);
        //
        // InputRegular input = new InputRegular(getBaseContext());
        //
        // StringBuffer sb = new StringBuffer();
        //
        // for (int i = 0; i < mPostLandlordInfos.recommendarray.size(); i++) {
        // if (i == 0) {
        // sb.append(mPostLandlordInfos.recommendarray.get(i).username);
        // } else if (i == 1) {
        // sb.append("、" + mPostLandlordInfos.recommendarray.get(i).username);
        // break;
        // }
        // }
        //
        // String result = "";
        // if (mPostLandlordInfos.recommendarray.size() > 2) {
        // result =
        // String.format("%s 等%s人赞过", sb.toString(), mPostLandlordInfos.recommendtotal);
        // } else {
        // result = String.format("%s 赞过", sb.toString());
        // }
        //
        // SpannableStringBuilder ssb = new SpannableStringBuilder(result);
        // praised.setText(input.parsePraise(mPostLandlordInfos.recommendarray, ssb,
        // new IRequest<RecommendInfo>() {
        //
        // @Override
        // public void request(RecommendInfo t) {
        // if (t == null) {
        // Intent intent = new Intent(getBaseContext(), ZanListActivity.class);
        // intent.putExtra("tid", mPostLandlordInfos.threadinfo.tid);
        // intent.putExtra("totalzan", mPostLandlordInfos.recommendtotal);
        // intent.putExtra("title", mPostLandlordInfos.threadinfo.subject);
        // startActivity(intent);
        // } else {
        // Intent intent =
        // new Intent(getBaseContext(),
        // com.xindaoapp.happypet.activity.MainActivity.class);
        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
        // UserInfoFragment.class.getCanonicalName());
        // Bundle bundle = new Bundle();
        // bundle.putString(Constants.KEY_UID, t.recommenduid);
        // bundle.putString(Constants.KEY_USERNAME, t.username);
        // bundle.putString(Constants.KEY_USERFACE, t.userface);
        // intent.putExtra(Constants.KEY_BUNDLE, bundle);
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // startActivity(intent);
        // }
        // }
        // }));
        // praised.setMovementMethod(LinkMovementMethod.getInstance());
        // vHeaderView.findViewById(R.id.l_praised).setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // Intent intent = new Intent(getBaseContext(), ZanListActivity.class);
        // intent.putExtra("tid", mPostLandlordInfos.threadinfo.tid);
        // intent.putExtra("totalzan", mPostLandlordInfos.recommendtotal);
        // intent.putExtra("title", mPostLandlordInfos.threadinfo.subject);
        // startActivity(intent);
        // }
        // });
        // } else {
        // vHeaderView.findViewById(R.id.l_praised).setVisibility(View.GONE);
        // }

    }

    /**
     * 点赞
     */
    private void parse() {
        if (UserState.isLogged(this)) {
            vPraiseView.setEnabled(false);
            if (!vImgPraise.isSelected()) {
                goPraise(vImgPraise);// 点赞动画
                getMoccaApi().praise(mForumTid, UserState.getUserUid(),
                        new IRequest<RecommendInfo>() {

                            @Override
                            public void request(RecommendInfo t) {
                                if (null != t) {
                                    vPraiseView.setEnabled(true);
                                    // showToast("点赞成功");
                                    mPostLandlordInfos.recommendtotal++;
                                    RecommendInfo info = new RecommendInfo();
                                    info.userface = UserState.getUser().userface;
                                    info.username = UserState.getUser().username;
                                    info.recommenduid = UserState.getUser().uid;
                                    mPostLandlordInfos.recommendarray.add(0, info);
                                    mPostLandlordInfos.threadinfo.myrecommend = 1;
                                    handlePraised();
                                } else {
                                    vPraiseView.setEnabled(true);
                                    vImgPraise.setSelected(false);
                                    showToast("点赞失败");
                                }
                            }
                        });
            } else {
                // 取消赞
                getMoccaApi().cancelPraise(mForumTid, new IRequest<BaseEntity>() {

                    @Override
                    public void request(BaseEntity t) {

                        vPraiseView.setEnabled(true);
                        if (null != t) {
                            if (t.getResult().equals("0")) {
                                // showToast("取消赞成功");
                                vImgPraise.setSelected(false);
                                mPostLandlordInfos.recommendtotal--;
                                RecommendInfo info = new RecommendInfo();
                                info.userface = UserState.getUser().userface;
                                info.username = UserState.getUser().username;
                                info.recommenduid = UserState.getUser().uid;
                                for (int i = 0; i < mPostLandlordInfos.recommendarray.size(); i++) {
                                    if (mPostLandlordInfos.recommendarray.get(i).recommenduid
                                            .equals(info.recommenduid)) {
                                        mPostLandlordInfos.recommendarray.remove(i);
                                        break;
                                    }
                                }
                                mPostLandlordInfos.threadinfo.myrecommend = 0;
                                handlePraised();
                            } else {
                                showToast(t.getMsg());
                            }
                        } else {
                            showToast(getResources().getString(R.string.net_error));
                        }


                    }
                });
            }
        }
    }

    private void goPraise(final ImageView view) {
        view.setSelected(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {


            final ObjectAnimator oa =
                    ObjectAnimator.ofInt(new ViewWrapper2(view), "width",

                    CommonUtil.dip2px(PostDetailActivity.this, 0),
                            CommonUtil.dip2px(PostDetailActivity.this, 40));
            final ObjectAnimator ob =
                    ObjectAnimator.ofInt(new ViewWrapper2(view), "height",

                    CommonUtil.dip2px(PostDetailActivity.this, 0),
                            CommonUtil.dip2px(PostDetailActivity.this, 40));
            oa.setInterpolator(new AccelerateDecelerateInterpolator());
            ob.setInterpolator(new AccelerateDecelerateInterpolator());
            oa.setDuration(250);
            ob.setDuration(250);


            final AnimatorSet set = new AnimatorSet();
            set.play(oa).with(ob);

            set.addListener(new AnimatorListener() {

                @Override
                public void onAnimationStart(Animator arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onAnimationRepeat(Animator arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onAnimationEnd(Animator arg0) {
                    // TODO Auto-generated method stub


                    ObjectAnimator oa2 =
                            ObjectAnimator.ofInt(new ViewWrapper2(view), "width",
                                    CommonUtil.dip2px(PostDetailActivity.this, 40),
                                    CommonUtil.dip2px(PostDetailActivity.this, 20));
                    ObjectAnimator ob2 =
                            ObjectAnimator.ofInt(new ViewWrapper2(view), "height",
                                    CommonUtil.dip2px(PostDetailActivity.this, 40),
                                    CommonUtil.dip2px(PostDetailActivity.this, 20));
                    oa2.setInterpolator(new AccelerateDecelerateInterpolator());
                    ob2.setInterpolator(new AccelerateDecelerateInterpolator());
                    oa2.setDuration(250);
                    ob2.setDuration(250);

                    AnimatorSet set2 = new AnimatorSet();
                    set2.play(oa2).with(ob2);
                    set2.start();

                }

                @Override
                public void onAnimationCancel(Animator arg0) {
                    // TODO Auto-generated method stub

                }
            });

            set.start();
        }
    }

    private class ViewWrapper2 {
        private final View mTarget;

        public ViewWrapper2(View target) {
            mTarget = target;
        }

        public int getWidth() {
            return mTarget.getLayoutParams().width;
        }

        public void setWidth(int width) {
            mTarget.getLayoutParams().width = width;
            mTarget.requestLayout();
        }

        public int getHeight() {
            return mTarget.getLayoutParams().height;
        }

        public void setHeight(int height) {
            mTarget.getLayoutParams().height = height;
            mTarget.requestLayout();
        }
    }


    private SharePopupWindow win;

    private void share() {
        // if (null == mAdapter) {
        // return;
        // }

        String url = "http://bbs.chinapet.com/threadwap-" + mForumTid + ".html";
        String temp = mPostLandlordInfos.threadinfo.forumname;
        if (temp.lastIndexOf("俱乐部") >= 0) {
            temp = temp.substring(0, temp.length() - 3);
        }
        win =
                new SharePopupWindow(PostDetailActivity.this,
                        mPostLandlordInfos.threadinfo.coverpath, true);
        win.setDefaultIconId(R.drawable.icon);
        win.setPostCome("threadshow");
        win.setPostTid(mForumTid);
        win.setInfors(
                PostDetailActivity.this,
                String.format("#尾巴圈宠物#分享一篇好帖子：“%s”%s，@尾巴圈 ，我的养宠神器！下载地址》%s",
                        mPostLandlordInfos.threadinfo.subject, url,
                        getString(R.string.app_download_url)),
                "【" + temp + "】" + mPostLandlordInfos.threadinfo.subject,
                "【" + temp + "】" + mPostLandlordInfos.threadinfo.subject, url).showAtLocation(
                findViewById(R.id.post_list), Gravity.BOTTOM, 0, 0);
        // win.setInfors(
        // PostDetailActivity.this,
        // String.format(mPostLandlordInfos.threadinfo.subject + "(分享自#尾巴圈#" + ")“尾巴圈下载地址：%s"
        // + " " + "(来自@尾巴圈)", url),
        // "【" + temp + "】" + mPostLandlordInfos.threadinfo.subject,
        // "【" + temp + "】" + mPostLandlordInfos.threadinfo.subject, url).showAtLocation(
        // findViewById(R.id.post_list), Gravity.BOTTOM, 0, 0);

        CommonUtil.addScreenBg(win, PostDetailActivity.this);
    }

    /** 拍照 */
    private void takePhoto() {
        mCameraFilePath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/happypet/pic"
                        + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        startActivityForResult(intent, PUBLISHPOSTS.CAMERA);
    }

    /**
     * 检查回复内容
     * 
     * @return
     */
    private boolean checkReplyInput() {
        if (mPictureAdapter.getDatas().size() > 0) {// 图片附件大于0
            return true;
        } else if (handleFlag != SWITCHSTATE.NONE) {// 有视频或者帖子引用
            return true;
        }
        if (TextUtils.isEmpty(mPostContent)) {
            Toast.makeText(getBaseContext(), "回复内容不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    enum SWITCHSTATE {
        NONE, TOOLS, PHOTO, VIDEO, POST, FACE
    }

    /**
     * 切换状态
     */
    private void switchViewState(SWITCHSTATE state) {
        if (state == SWITCHSTATE.NONE) {
            vFaceContainerView.setVisibility(View.GONE);
            vPhotosGridView.setVisibility(View.GONE);
            vQuoteInfoView.setVisibility(View.GONE);
            vSelectView.setVisibility(View.GONE);
            vAccessoryChooseContainerView.setVisibility(View.GONE);
        } else {
            vAccessoryChooseContainerView.setVisibility(View.VISIBLE);
            vFaceContainerView.setVisibility(View.GONE);
            vPhotosGridView.setVisibility(View.GONE);
            vQuoteInfoView.setVisibility(View.GONE);
            vSelectView.setVisibility(View.GONE);
            if (state == SWITCHSTATE.TOOLS) {// 显示工具栏
                // 需要判断当前是否已经有照片了
                if (mPictureAdapter.getDatas().size() > 0) {
                    vPhotosGridView.setVisibility(View.VISIBLE);
                } else if (handleFlag != SWITCHSTATE.NONE) {
                    vQuoteInfoView.setVisibility(View.VISIBLE);
                } else {
                    vSelectView.setVisibility(View.VISIBLE);
                }
            } else if (state == SWITCHSTATE.PHOTO) {
                vPhotosGridView.setVisibility(View.VISIBLE);
            } else if (state == SWITCHSTATE.VIDEO || state == SWITCHSTATE.POST) {
                handleFlag = state;
                vQuoteInfoView.setVisibility(View.VISIBLE);
            } else if (state == SWITCHSTATE.FACE) {
                vFaceContainerView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void hideInputMethod() {
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    private void showInputMethod() {
        // 打开软键盘
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PUBLISHPOSTS.CAMERA && resultCode == RESULT_OK) {// 拍照完成
            handleCameraPhotos(data);
        } else if (requestCode == PUBLISHPOSTS.PHOTOALBUM && resultCode == RESULT_OK) {// 选择照片
            handlePickPhotos(data);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_PICK_VIDEO && resultCode == RESULT_OK) {// 选择视频
            handlePickVideo(data);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_QUOTE_POST && resultCode == RESULT_OK) {// 引用帖子
            handleQuotePost(data);
        } else if (requestCode == PUBLISHPOSTS.PHOTO_AMEND && resultCode == RESULT_OK) {// @提醒好友
            photoAmend(data);
        } else if (requestCode == 937 && resultCode == RESULT_OK) {//
            handleShareWeiba(data, false);
        } else if (requestCode == 654 && resultCode == RESULT_OK) {//
            handleShareWeiba(data, true);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_APPLY && resultCode == RESULT_OK) {// 申请试用
            // handleApplySuccess();
        }

        if (null != win) {
            UMSsoHandler ssoHandler = win.mController.getConfig().getSsoHandler(requestCode);
            if (ssoHandler != null) {
                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }

    }

    /**
     * 分享尾巴好友
     */
    private void handleShareWeiba(Intent data, boolean b) {
        // TODO Auto-generated method stub

        if (b) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getShareToWeiba(mTidlist, mForumTid,
                            data.getStringExtra(Constants.SHARECONTENT) + "",
                            new IRequest<ShareToWeibaResult>() {

                                @Override
                                public void request(ShareToWeibaResult t) {
                                    if (null != t) {
                                        showToast(t.getMsg());

                                    } else {
                                        showToast(getResources().getString(R.string.net_error));
                                    }

                                    // shareSend(MoccaApi.VALUE_THREAD_SHOW);
                                }
                            });
        } else {

            mTidlist = data.getStringExtra(Constants.KEY_UID);
            Intent intent = new Intent(getApplicationContext(), ShareWeibaDialogActivity.class);
            intent.putExtra("title", mTitle);
            startActivityForResult(intent, 654);
        }



    }

    /**
     * @param data 引用帖子返回
     */
    private void handleQuotePost(Intent data) {
        if (data != null) {
            switchViewState(SWITCHSTATE.POST);
            ImageLoader.getInstance().displayImage(data.getStringExtra(Constants.KEY_POST_COVER),
                    vQuoteIcon);
            vQuoteTitle.setText(data.getStringExtra(Constants.KEY_POST_NAME));
            vQuoteInfoView.setTag(data);
        }
    }

    /**
     * 选择视频返回
     * 
     * @param data
     */
    private void handlePickVideo(Intent data) {
        if (data != null) {
            switchViewState(SWITCHSTATE.VIDEO);
            ImageLoader.getInstance().displayImage(
                    data.getStringExtra(Constants.KEY_VIDEO_IMAGE_URL), vQuoteIcon);
            vQuoteTitle.setText(data.getStringExtra(Constants.KEY_VIDEO_NAME));
            vQuoteInfoView.setTag(data);
        }
    }


    /**
     * @param data 从相册返回
     */
    private void handlePickPhotos(Intent data) {
        if (null != data) {
            switchViewState(SWITCHSTATE.PHOTO);
            // 选择出新的
            ArrayList<String> list = data.getStringArrayListExtra(Constants.PARAM_PHOTO_LIST);
            ArrayList<String> oldList = mPictureAdapter.getDatas();

            final ArrayList<KeyValuePair<String, Integer>> needUploadInfos =
                    new ArrayList<KeyValuePair<String, Integer>>();
            for (int i = 0; i < list.size(); i++) {
                if (!oldList.contains(list.get(i))) {
                    needUploadInfos.add(new KeyValuePair<String, Integer>(list.get(i), 0));
                }
            }
            postFiles(needUploadInfos);
            resetAdapter(list);
        }
    }

    /**
     * @param data 拍照返回
     */
    private void handleCameraPhotos(Intent data) {
        switchViewState(SWITCHSTATE.PHOTO);
        ArrayList<String> list = mPictureAdapter.getDatas();
        list.add(mCameraFilePath);
        // 已经存在的
        List<KeyValuePair<String, Integer>> pairs = new ArrayList<KeyValuePair<String, Integer>>();
        pairs.add(new KeyValuePair<String, Integer>(mCameraFilePath, 0));
        postFiles(pairs);
        resetAdapter(list);
    }

    /** 上传文件（支持多张） */
    private void postFiles(List<KeyValuePair<String, Integer>> list) {
        if (mPostQueue != null)
            mPostQueue.addQueue(list);
        else if (null != UserState.getUserUid() && mPostLandlordInfos != null
                && mPostLandlordInfos.threadinfo != null
                && mPostLandlordInfos.threadinfo.fid != null) {
            mPostQueue =
                    new PostQueueImpl(getBaseContext(), UserState.getUserUid(),
                            mPostLandlordInfos.threadinfo.fid, System.currentTimeMillis(),
                            iUploadProgress);
        }
    }

    /**
     * 正式回复
     */
    private void post() {
        hideInputMethod();
        HappyPetApplication.get().getUploaQueueImpl().addQueue(mPostQueue);

        List<KeyValuePair<String, Integer>> list = new ArrayList<KeyValuePair<String, Integer>>();
        // 组装图片
        for (int i = 0; i < mPictureAdapter.getDatas().size(); i++) {
            list.add(new KeyValuePair<String, Integer>(new File(mPictureAdapter.getDatas().get(i))
                    .getAbsolutePath(), new File(mPictureAdapter.getDatas().get(i))
                    .getAbsolutePath().lastIndexOf(".mp4") >= 0 ? 1 : 0));
        }

        // 组装内容
        JSONObject jo = null;
        if (handleFlag != SWITCHSTATE.NONE) {// 引用视频
            if (SWITCHSTATE.VIDEO == handleFlag) {
                Intent data = (Intent) vQuoteInfoView.getTag();
                try {
                    jo = new JSONObject();
                    jo.put("title", data.getStringExtra(Constants.KEY_VIDEO_NAME));
                    jo.put("body", data.getStringExtra(Constants.KEY_VIDEO_DESCRIPTION));
                    jo.put("url", data.getStringExtra(Constants.KEY_VIDEO_URL));
                    jo.put("coverpath", data.getStringExtra(Constants.KEY_VIDEO_IMAGE_URL));
                } catch (Exception e) {
                }
            } else if (SWITCHSTATE.POST == handleFlag) {
                Intent data = (Intent) vQuoteInfoView.getTag();
                mPostContent +=
                        String.format("[appquotethread]%s[/appquotethread]",
                                data.getStringExtra(Constants.KEY_POST_TID));
            }
        }
        mPostContent = CommonUtil.replaceAllKuoHao(mPostContent);
        mPostQueue.addQueue(mPostContent, mForumTid, mLayerPid, list,
                jo == null ? "" : jo.toString());

        // 清空图片列表
        mPictureAdapter.resetList(new ArrayList<String>());
        emojicon = "";
        mPostContent = "";
        mCameraFilePath = "";
        handleFlag = SWITCHSTATE.NONE;
        vPostContent.getEditableText().clear();
        switchViewState(SWITCHSTATE.NONE);
    }

    private void resetAdapter(ArrayList<String> picUrList) {
        mPictureAdapter.resetList(picUrList);
        mPictureAdapter.notifyDataSetChanged();
    }

    /**
     * 图片修改
     * 
     * @param data
     */
    private void photoAmend(Intent data) {
        if (null != data) {
            mPictureAdapter.resetList(data.getStringArrayListExtra(Constants.PARAM_PHOTO_LIST));
            mPictureAdapter.notifyDataSetChanged();
        }
    }

    private final IUploadProgress iUploadProgress = new IUploadProgress() {

        @Override
        public void success() {}

        @Override
        public void start(int current, int count) {}

        @Override
        public void progress(int progress) {}

        @Override
        public void pause() {}

        @Override
        public void error(String msg) {}

        @Override
        public void cancel() {}
    };

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // 通过判断点击的位置是否等于图片的数据
            if (mPictureAdapter.getDatas().size() == position) {
                showPickPhotoPopupWindow();
            } else {
                // 进入编辑页面
                Intent intent = new Intent(PostDetailActivity.this, PictureEditorActivity.class);
                intent.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST,
                        mPictureAdapter.getDatas());
                intent.putExtra(Constants.PARAM_PHOTO_POSITION, position);
                startActivityForResult(intent, PUBLISHPOSTS.PHOTO_AMEND);
            }
        }
    };

    /** 初始化表情 */
    private void initFaceView() {
        vPointContainer.removeAllViews();
        View view;
        for (int i = 0; i < 4; i++) {
            // 添加点view对象
            view = new View(this);
            view.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.point_background_postmessage));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
            lp.leftMargin = 10;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            vPointContainer.addView(view);
        }
        vFaceViewPager.setAdapter(mPagerAdapter);
        vFaceViewPager.setOnPageChangeListener(mFacePageChangeListener);
        vPointContainer.getChildAt(0).setEnabled(true);
    }

    private final OnPageChangeListener mFacePageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < vPointContainer.getChildCount(); i++) {
                if (arg0 == i) {
                    vPointContainer.getChildAt(i).setEnabled(true);
                } else {
                    vPointContainer.getChildAt(i).setEnabled(false);
                }
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    };

    private String emojicon = "";

    // 填充ViewPager的数据适配器
    private final PagerAdapter mPagerAdapter = new PagerAdapter() {
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        private int[] getImgs(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgs0;
                case 1:
                    return Expressions.expressionImgs1;
                case 2:
                    return Expressions.expressionImgs2;
                case 3:
                    return Expressions.expressionImgs3;
                default:
                    return null;
            }
        }

        private String[] getImgNames(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgNames0;
                case 1:
                    return Expressions.expressionImgNames1;
                case 2:
                    return Expressions.expressionImgNames2;
                case 3:
                    return Expressions.expressionImgNames3;
                default:
                    return null;
            }
        }

        @Override
        public Object instantiateItem(View container, int position) {
            View view = View.inflate(getBaseContext(), R.layout.layout_post_face, null);
            GridView gridView = (GridView) view.findViewById(R.id.gridview);
            final int[] images = getImgs(position);
            final String[] imageNames = getImgNames(position);
            FaceAdapter adapter = new FaceAdapter(images);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                    Bitmap bitmap = null;
                    bitmap =
                            BitmapFactory.decodeResource(getResources(), images[position
                                    % images.length]);
                    ImageSpan imageSpan = new ImageSpan(PostDetailActivity.this, bitmap);
                    SpannableString spannableString =
                            new SpannableString(imageNames[position].substring(1,
                                    imageNames[position].length() - 1));
                    spannableString.setSpan(imageSpan, 0, imageNames[position].length() - 2,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // 编辑框设置数据
                    String str = vPostContent.getText().toString();
                    str = CommonUtil.replaceAllKuoHao(str);
                    emojicon = str + imageNames[position];
                    SpannableStringBuilder ssb =
                            CommonUtil.convetToHtml(CommonUtil.parseEmoji(emojicon),
                                    getBaseContext());
                    vPostContent.setText(ssb);
                    vPostContent.setSelection(vPostContent.getText().length());
                }

            });
            ((ViewPager) container).addView(view);
            return view;
        }
    };



    class FaceAdapter extends BaseAdapter {
        private final int[] list;

        public FaceAdapter(int[] list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView =
                        View.inflate(PostDetailActivity.this, R.layout.singleexpression, null);
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setImageResource(list[position]);
            LayoutParams params =
                    new LayoutParams(CommonUtil.dip2px(PostDetailActivity.this, 170) / 3,
                            CommonUtil.dip2px(PostDetailActivity.this, 170) / 3);
            holder.icon.setLayoutParams(params);
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
        }

    }

    /**
     * 选择图片
     */
    private void showPickPhotoPopupWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.layout_pick_photo, null);

        CommonUtil.addScreenBg(popupWindow, PostDetailActivity.this);

        view.findViewById(R.id.btn_take_photo).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (mPictureAdapter.getDatas().size() == Constants.PUBLISHPOSTS_COUNTS) {
                    Toast.makeText(getBaseContext(),
                            String.format("最多选择%s张图片", Constants.PUBLISHPOSTS_COUNTS),
                            Toast.LENGTH_SHORT).show();
                } else {
                    takePhoto();
                }
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_pick_photo).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PostDetailActivity.this, PictureListActivity.class);
                // 传递当前已经选择的图片
                intent.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST,
                        mPictureAdapter.getDatas());
                startActivityForResult(intent, PUBLISHPOSTS.PHOTOALBUM);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.post_list),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 引用视频
     */
    private void showQuoteVideoPopupWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.layout_quote_video, null);

        CommonUtil.addScreenBg(popupWindow, PostDetailActivity.this);
        view.findViewById(R.id.btn_youku).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), QuoteVideoActivity.class);
                intent.putExtra(Constants.KEY_VIDEO_TYPE, VIDEO_TYPE.YOUKU.ordinal());
                startActivityForResult(intent, Constants.PUBLISHPOSTS.REQUEST_PICK_VIDEO);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_tudou).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), QuoteVideoActivity.class);
                intent.putExtra(Constants.KEY_VIDEO_TYPE, VIDEO_TYPE.TUDOU.ordinal());
                startActivityForResult(intent, Constants.PUBLISHPOSTS.REQUEST_PICK_VIDEO);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.post_list),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 删除引用视频
     */
    private void showDeleteVideoWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.pop_delete_video, null);
        CommonUtil.addScreenBg(popupWindow, PostDetailActivity.this);
        view.findViewById(R.id.btn_choose_video).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
                showQuoteVideoPopupWindow();
            }
        });
        view.findViewById(R.id.btn_delete).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleFlag = SWITCHSTATE.NONE;
                switchViewState(SWITCHSTATE.TOOLS);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.post_list),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    /**
     * 删除引用帖子
     */
    private void showDeletePostWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        CommonUtil.addScreenBg(popupWindow, PostDetailActivity.this);
        View view = View.inflate(getBaseContext(), R.layout.pop_delete_video, null);
        ((TextView) view.findViewById(R.id.btn_choose_video)).setText("引用帖子");
        view.findViewById(R.id.btn_choose_video).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                quotePost();
            }
        });
        view.findViewById(R.id.btn_delete).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handleFlag = SWITCHSTATE.NONE;
                switchViewState(SWITCHSTATE.TOOLS);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.post_list),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 右上角工具按钮
     */
    private void showMoreToolsWindow() {
        if (mPostLandlordInfos == null) {
            return;
        }
        final SelectPicPopupWindow popupWindow =
                new SelectPicPopupWindow(false, R.color.black, this);
        // CommonUtil.addScreenBg(popupWindow, PostDetailActivity.this);

        View view = View.inflate(getBaseContext(), R.layout.pop_tools_more, null);

        ImageView collect = (ImageView) view.findViewById(R.id.img_collect);
        collect.setSelected(mPostLandlordInfos.threadinfo.myfavorite == 1 ? true : false);
        collect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (!UserState.isLogged(PostDetailActivity.this)) {
                    return;
                }
                if (mPostLandlordInfos.threadinfo.myfavorite == 0) {
                    getMoccaApi().collect(mForumTid, UserState.getUserUid(),
                            new IRequest<BaseEntity>() {

                                @Override
                                public void request(BaseEntity t) {

                                    if (null != t) {
                                        if (t.getResult().equals("0")) {
                                            mPostLandlordInfos.threadinfo.myfavorite = 1;
                                            showToast("收藏成功");
                                        } else {
                                            showToast(t.getMsg());
                                        }
                                    } else {
                                        showToast(getResources().getString(R.string.net_error));
                                    }


                                }
                            });
                } else {
                    getMoccaApi().cancelCollect(mForumTid, UserState.getUserUid(),
                            new IRequest<BaseEntity>() {

                                @Override
                                public void request(BaseEntity t) {

                                    if (null != t) {
                                        if (t.getResult().equals("0")) {
                                            mPostLandlordInfos.threadinfo.myfavorite = 0;
                                            showToast("取消收藏成功");
                                        } else {
                                            showToast(t.getMsg());
                                        }
                                    } else {
                                        showToast(getResources().getString(R.string.net_error));
                                    }
                                }
                            });
                }
            }
        });
        view.findViewById(R.id.img_skip_page).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
                new SkipPageDialog(
                        PostDetailActivity.this,
                        R.style.Default_Dialog_Style,
                        mCurrentPage,
                        mPostLandlordInfos.threadinfo.replies % 10 == 0 ? mPostLandlordInfos.threadinfo.replies / 10
                                : mPostLandlordInfos.threadinfo.replies / 10 + 1,
                        new IRequest<Integer>() {

                            @Override
                            public void request(Integer t) {
                                loadLayer(t);
                            }
                        }).show();
            }
        });
        view.findViewById(R.id.img_report).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();

                if (UserState.isLogged(PostDetailActivity.this)) {
                    if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2
                            || UserState.getUser().adminid == 3) {
                        new AlertDialog.Builder(PostDetailActivity.this).setMessage("确定删除该帖子")
                                .setTitle("提示")
                                .setNegativeButton("删除", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        getMoccaApi().report(mForumTid, UserState.getUserUid(),
                                                mPostLandlordInfos.threadinfo.pid,
                                                new IRequest<BaseEntity>() {

                                                    @Override
                                                    public void request(BaseEntity t) {
                                                        if (null != t && t.getResult().equals("0")) {
                                                            Toast.makeText(getBaseContext(),
                                                                    "删除成功", Toast.LENGTH_SHORT)
                                                                    .show();
                                                            finish();
                                                        } else {
                                                            Toast.makeText(getBaseContext(),
                                                                    "删除失败", Toast.LENGTH_SHORT)
                                                                    .show();
                                                        }
                                                    }
                                                });
                                    }
                                }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    } else {
                        getMoccaApi().report(mForumTid, UserState.getUserUid(),
                                mPostLandlordInfos.threadinfo.pid, new IRequest<BaseEntity>() {

                                    @Override
                                    public void request(BaseEntity t) {
                                        if (null != t) {
                                            if (t.getResult().equals("0")) {
                                                mPostLandlordInfos.threadinfo.myfavorite = 0;
                                                showToast("举报成功");
                                            } else {
                                                showToast(t.getMsg());
                                            }
                                        } else {
                                            showToast(getResources().getString(R.string.net_error));
                                        }

                                    }


                                });
                    }

                }
            }
        });
        // popupWindow.init(view).showAtLocation(findViewById(R.id.title),
        // Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupWindow.init(view).showAsDropDown(findViewById(R.id.title));
    }

    public class SelectPicPopupWindow extends PopupWindow {
        private boolean isStyle = true;
        private int colorRes;

        public SelectPicPopupWindow(Activity context) {
            super(context);
        }

        public SelectPicPopupWindow(boolean isStyle, Activity context) {
            super(context);
            this.isStyle = isStyle;
        }

        public SelectPicPopupWindow(boolean isStyle, int colorRes, Activity context) {
            super(context);
            this.isStyle = isStyle;
            this.colorRes = colorRes;
        }

        public SelectPicPopupWindow init(View view) {
            this.setContentView(view);
            this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            if (isStyle) {
                this.setAnimationStyle(R.style.PopupAnimation);
            }
            if (colorRes != 0) {
                this.setBackgroundDrawable(new ColorDrawable(getResources().getColor(colorRes)));
            } else {
                this.setBackgroundDrawable(new ColorDrawable(getResources().getColor(
                        R.color.transparent)));
            }
            setFocusable(true);
            return this;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mSendReceiver);
        if (mPostContentManager != null) {
            mPostContentManager.stopPlayback();
        }
        // 退出时释放连接
        mIat.cancel();
        mIat.destroy();
        System.gc();
    }

    public class SendReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra(Constants.KEY_POST_TID).equals(mForumTid)) {
                PostLayerInfo info = null;
                try {
                    mPostLandlordInfos.threadinfo.replies++;
                    String stringExtra = intent.getStringExtra("finish");
                    JSONObject jsonObj = new JSONObject(stringExtra);
                    String str = jsonObj.getString("postinfo");
                    info = JSON.parseObject(str, PostLayerInfo.class);
                    info.ratesum = "0";
                    if (lay_order.getVisibility() == View.GONE) {
                        lay_order.setVisibility(View.VISIBLE);
                    }
                    if (bottom_line.getVisibility() == View.GONE) {
                        bottom_line.setVisibility(View.VISIBLE);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null != mAdapter) {
                    mAdapter.getResult().add(info);
                    mAdapter.notifyDataSetChanged();
                } else {
                    List<PostLayerInfo> list = new ArrayList<PostLayerInfo>();
                    list.add(info);
                    mAdapter =
                            new PostsDetailAdapter(mOrder, mPostLandlordInfos.threadinfo,
                                    mForumTid, vLookMode.isSelected(), PostDetailActivity.this,
                                    list, Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                                    R.layout.list_item_post_detail_layer, R.layout.item_loading);
                    mAdapter.setActivity(PostDetailActivity.this);
                    vPullToRefreshListView.setAdapter(mAdapter);
                }
                handleCommentCount();
            }

        }

    }

    private void initPopForDashang() {
        // TODO Auto-generated method stub
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        /* 设置显示menu布局 view子VIEW */
        View sub_view = mLayoutInflater.inflate(R.layout.layout_pop_for_dashang, null);

        bt_no = (Button) sub_view.findViewById(R.id.bt_no);
        bt_ok = (Button) sub_view.findViewById(R.id.bt_ok);
        lay_scroll = (RelativeLayout) sub_view.findViewById(R.id.lay_scroll);
        iv_refresh = (ImageView) sub_view.findViewById(R.id.iv_refresh);
        et_reason = (EditText) sub_view.findViewById(R.id.et_reason);
        tv_rest = (TextView) sub_view.findViewById(R.id.tv_rest);
        pb_load = (ProgressBar) sub_view.findViewById(R.id.pb_load);

        iv_one = (TextView) sub_view.findViewById(R.id.iv_one);
        iv_two = (TextView) sub_view.findViewById(R.id.iv_two);
        iv_three = (TextView) sub_view.findViewById(R.id.iv_three);
        iv_four = (TextView) sub_view.findViewById(R.id.iv_four);
        iv_five = (TextView) sub_view.findViewById(R.id.iv_five);

        iv_one.setOnClickListener(mDaShangListener);
        iv_two.setOnClickListener(mDaShangListener);
        iv_three.setOnClickListener(mDaShangListener);
        iv_four.setOnClickListener(mDaShangListener);
        iv_five.setOnClickListener(mDaShangListener);

        // mDaShangCount = 1;
        // iv_one.setSelected(true);

        // RelativeLayout.LayoutParams layoutParams =
        // (android.widget.RelativeLayout.LayoutParams) lay_scroll.getLayoutParams();
        // layoutParams.width = LayoutParams.MATCH_PARENT;
        // layoutParams.height = CommonParameter.sScreenHeight / 2;
        // lay_scroll.setLayoutParams(layoutParams);


        /* 第一个参数弹出显示view 后两个是窗口大小 */
        mPopupWindow =
                new PopupWindow(sub_view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        /* 设置背景显示 */
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        /* 设置系统动画 */
        // mPopupWindow2.setAnimationStyle(R.style.Pop_Custom);
        // mPopupWindow2.setAnimationStyle(android.R.style.Animation_Dialog);
        /* 设置点击menu以外其他地方以及返回键退出 */
        mPopupWindow.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow.setOutsideTouchable(true);

        iv_one.performClick();

        // mPopupWindow.setOnDismissListener(new OnDismissListener() {
        // @Override
        // public void onDismiss() {
        // // TODO Auto-generated method stub
        //
        // et_reason.setText("");
        //
        //
        // }
        // });

        bt_no.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow.dismiss();
            }
        });
        bt_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 确定打赏

                if (isLoadRest) {
                    mPopupWindow.dismiss();
                    String pid =
                            mFrom.equals("item") ? otherPid : mPostLandlordInfos.threadinfo.pid;
                    getMoccaApi().daShang(
                            mForumTid,
                            pid,
                            et_reason.getText().toString().equals("") ? "宠物中国有你更精彩" : et_reason
                                    .getText().toString(), mDaShangCount + "",
                            new IRequest<BaseEntity>() {

                                @Override
                                public void request(BaseEntity t) {
                                    // TODO Auto-generated method stub
                                    if (t != null) {
                                        if (t.getResult().equals("0")) {
                                            et_reason.setText("");

                                            if (mFrom.equals("item")) {
                                                mSelectedLayerInfo.ratesum =
                                                        Integer.parseInt(mSelectedLayerInfo.ratesum)
                                                                + mDaShangCount + "";

                                                // if (mPostLandlordInfos.threadinfo.authorid
                                                // .equals(mSelectedLayerInfo.authorid)) {
                                                // tv_dashangsum.setVisibility(View.VISIBLE);
                                                // mPostLandlordInfos.threadinfo.ratesum =
                                                // Integer.parseInt(mPostLandlordInfos.threadinfo.ratesum)
                                                // + mDaShangCount + "";
                                                // tv_dashangsum
                                                // .setText("+"
                                                // + mPostLandlordInfos.threadinfo.ratesum);
                                                // }
                                                mAdapter.notifyDataSetChanged();

                                            } else {
                                                tv_dashangsum.setVisibility(View.VISIBLE);
                                                mPostLandlordInfos.threadinfo.ratesum =
                                                        Integer.parseInt(mPostLandlordInfos.threadinfo.ratesum)
                                                                + mDaShangCount + "";
                                                tv_dashangsum.setText("+"
                                                        + mPostLandlordInfos.threadinfo.ratesum);
                                                mAdapter.notifyDataSetChanged();

                                            }
                                            showToast("打赏成功!");
                                        } else {
                                            showToast(t.getMsg());
                                        }

                                    } else {
                                        // showToast("网络链接异常,请稍后再试!");
                                        showToast(getResources().getString(R.string.net_error));
                                    }
                                }
                            });
                }
                // else {
                // showToast("请先刷新剩余尾巴数!");
                // }

            }
        });


        operatingAnim =
                AnimationUtils.loadAnimation(PostDetailActivity.this, R.anim.rotateanimation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);

        iv_refresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (operatingAnim != null) {
                    iv_refresh.startAnimation(operatingAnim);
                }
                getRest();
            }
        });

        mPopupWindow.update();

        if (UserState.getUser() == null) {
            return;
        }

        if (UserState.getUser().adminid == 1 || UserState.getUser().adminid == 2) {
            getRest();
        } else if (UserState.getUser().adminid == 3
                && UserState.getUser().moderatefids.contains("'"
                        + mPostLandlordInfos.threadinfo.fid + "'")) {
            getRest();
        }


    }

    OnClickListener mDaShangListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.iv_one:
                    giveWeiBaCount(1);
                    break;
                case R.id.iv_two:
                    giveWeiBaCount(2);
                    break;
                case R.id.iv_three:
                    giveWeiBaCount(3);
                    break;
                case R.id.iv_four:
                    giveWeiBaCount(4);
                    break;
                case R.id.iv_five:
                    giveWeiBaCount(5);
                    break;
                default:
                    break;
            }

        }
    };

    protected void getRest() {
        getMoccaApi().getRestDaShangWeiBa(new IRequest<DaShangRest>() {

            @Override
            public void request(DaShangRest t) {
                // TODO Auto-generated method stub

                if (operatingAnim != null) {
                    iv_refresh.clearAnimation();
                }

                if (t != null && t.result.equals("0")) {
                    tv_rest.setText(t.maxratetoday);
                    isLoadRest = true;
                    mRestCount = Integer.parseInt(t.maxratetoday);
                }
            }
        });

    }

    protected void giveWeiBaCount(int i) {
        // TODO Auto-generated method stub
        switch (i) {
            case 1:
                setDefaultCount();
                iv_one.setSelected(true);
                mDaShangCount = 1;
                break;
            case 2:
                setDefaultCount();
                iv_two.setSelected(true);
                mDaShangCount = 2;
                break;
            case 3:
                setDefaultCount();
                iv_three.setSelected(true);
                mDaShangCount = 3;
                break;
            case 4:
                setDefaultCount();
                iv_four.setSelected(true);
                mDaShangCount = 4;
                break;
            case 5:
                setDefaultCount();
                iv_five.setSelected(true);
                mDaShangCount = 5;
                break;
            default:
                break;
        }

    }

    private void setDefaultCount() {
        // TODO Auto-generated method stub
        iv_one.setSelected(false);
        iv_two.setSelected(false);
        iv_three.setSelected(false);
        iv_four.setSelected(false);
        iv_five.setSelected(false);

    }

    private void showDaShangPop() {
        // TODO Auto-generated method stub
        getRest();
        mPopupWindow.showAtLocation(findViewById(R.id.post_list), Gravity.CENTER, 0, 0);
    }

    @Override
    public void goToDS(PostLayerInfo info) {
        // TODO Auto-generated method stub
        mSelectedLayerInfo = info;
        otherPid = info.pid;
        mFrom = "item";
        showDaShangPop();
    }

    @Override
    public void setCurrentPage(int current) {
        // TODO Auto-generated method stub
        // mCurrentPage = current;
    }


    /**
     * 初始化监听器。
     */
    private final InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败,错误码：" + code);
            }
        }
    };

    private void showTip(String text) {
        showToast.setText(text);
        // showToast.show();
    }



    /** 听写监听器。 */
    private final RecognizerListener recognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            showTip("开始说话");
        }


        @Override
        public void onError(SpeechError error) {
            // Toast.makeText(PostDetailActivity.this, error.getPlainDescription(true),
            // Toast.LENGTH_LONG).show();

            hidenText.setText(error.getPlainDescription(true));
            tv_sure.setText("再说一次");
        }

        @Override
        public void onEndOfSpeech() {

            showTip("结束说话");
        }



        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            // Dialog.di
            String text = JsonParser.parseIatResult(results.getResultString());
            vPostContent.append(text);
            vPostContent.setSelection(vPostContent.length());
            if (isLast) {
                // TODO 最后的结果
                dialog.dismiss();
                showTip("最后的结果");
            }
        }

        @Override
        public void onVolumeChanged(int volume) {
            // showTip("当前正在说话，音量大小：" + volume);
            if (volume < 2) {
                voiceImageView.setBackgroundResource(R.drawable.talk_01);
            } else if (volume < 10) {
                voiceImageView.setBackgroundResource(R.drawable.talk_02);
            } else if (volume < 20) {
                voiceImageView.setBackgroundResource(R.drawable.talk_03);
            } else if (volume < 30) {
                voiceImageView.setBackgroundResource(R.drawable.talk_04);
            }
        }


        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {}
    };
    private ImageView order;
    private Dialog dialog;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // 1.5.2 上线禁用该功能
        // if (keyCode == KeyEvent.KEYCODE_BACK) {
        //
        // final String postText = vPostContent.getText().toString();
        // if (!TextUtils.isEmpty(postText)) {
        // new AlertDialog.Builder(PostDetailActivity.this).setMessage("保存消息到草稿箱吗?")
        // .setNegativeButton("保存", new DialogInterface.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        // // mForumTid
        // SharePrefUtil.saveString(PostDetailActivity.this, mForumTid,
        // postText);
        // PostDetailActivity.this.finish();
        // }
        //
        // }).setPositiveButton("放弃", new DialogInterface.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        // PostDetailActivity.this.finish();
        // }
        // }).setCancelable(true).show();
        //
        // return true;
        // } else {
        // SharePrefUtil.remove(PostDetailActivity.this, mForumTid);
        // }
        // }
        return super.onKeyDown(keyCode, event);
    }
}
